import { Body, Controller, Get, Post, Res, UseInterceptors, Request, HttpException, HttpStatus } from '@nestjs/common';
import { ValidRSAInterceptor } from 'src/interceptor/validRSA';
import { ValidTokenInterceptor } from 'src/interceptor/validToken';
import { apibefore } from 'src/router';
import { WatchRecord } from './watchRecord.entity';
import { WatchRecordService } from './watchRecord.service';
import Redis from 'ioredis';
import { InjectRedis } from '@nestjs-modules/ioredis';
import {
  RedisKey
} from './watchRecord.setting'

let {
  redisKeyWatchRecord,
  redisKeyWatchRecordIc
} = RedisKey

@Controller(apibefore('/watchRecord'))
@UseInterceptors(ValidTokenInterceptor)
@UseInterceptors(ValidRSAInterceptor)
export class WatchRecordController {
  constructor(private readonly service: WatchRecordService,
    @InjectRedis() private readonly redis: Redis
  ) {}

  @Post('/create')
  async create(@Body() data: any, @Request() req) {
    const wx_user = req.headers.wx_user
    let saveData = new WatchRecord();
    saveData.video_id = data.video_id
    saveData.wx_user = wx_user
    saveData.create_time = new Date()

    let isMember = await this.redis.sismember(redisKeyWatchRecord + wx_user, data.video_id)
    if(isMember != 1){
      await this.redis.sadd(redisKeyWatchRecord + wx_user, data.video_id)
    }
    if(data.ic_group){
      let isMember = await this.redis.sismember(redisKeyWatchRecordIc + wx_user, data.ic_group)
      if(isMember != 1){
        await this.redis.sadd(redisKeyWatchRecordIc + wx_user, data.ic_group)
      }
    }
    await this.service.create(saveData, data.work_type, data.ic_group);
    return true
  }
  @Get('/findAll')
  async findAll(){
    return await this.service.findAll()
  }

  @Post('/create_batch')
  async create_batch(@Body() data: any, @Request() req){
    const wx_user = req.headers.wx_user
    let ids = data.ids, ics = data.ics
    let error = await this.service.create_batch(wx_user, data.work_type, ids, ics)
    if(error){
      if(error.code === 'ER_DUP_ENTRY'){
        let idsn = [], icsn = [], numberk = 4
        if(error.query.indexOf('INSERT INTO `watch_record`') > -1){
          numberk = 3
        }
        let len = error.parameters.length / numberk
        for(let i = 0; i < len; i++){
          let item = error.parameters[i * numberk]
          if(numberk === 3){
            idsn.push(item)
          }else{
            icsn.push(item)
          }
        }
        console.log(idsn, icsn)
        return {ids: idsn, ics: icsn}
      }else{
        return new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }else{
      return {ids: ids, ics: ics}
    }
  }
}
